package com.xgkj.diyiketang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.easemob.easeui.domain.EaseUser;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskResultCode;
import com.xgkj.diyiketang.hxsdk.DemoHelper;
import com.xgkj.diyiketang.hxsdk.PreferenceManager;
import com.xgkj.diyiketang.task.BisaibaomingTask;
import com.xgkj.diyiketang.task.GetVerifyCodeTask;
import com.xgkj.diyiketang.task.IsNeedSchoolTask;
import com.xgkj.diyiketang.task.UpdateIconTask;
import com.xgkj.diyiketang.task.UpdateNickOrSignTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.RoundImageView;
import com.xgkj.diyiketang.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class CanjiahuodongActivity extends BaseActivity implements View.OnClickListener{
    private final String TAG = getClass().getSimpleName();
    private Context mContext;
    private RelativeLayout headImgLayout;
    private RelativeLayout nickNameLayout;
    private RelativeLayout personSigatureLayout;
    private RoundImageView mHeadImageView;
    private ClearableEditText nickNameText;
    private ClearableEditText personSigatureText;
    //    private ClearableEditText userSex;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private File mFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    private int taskId = -1;
    private EatShowUserInfo userInfo;
    private String old_url;
    private PopupWindow mPopWindow;
    private TextView sexView;
    private TextView saveText;
    private int saveTaskId = -1;
    private String mNick;
    private String mSign;
    private boolean sexB;
    private String mSexString;
    private ClearableEditText codeEdit;
    private String codeS;
    private ClearableEditText ageEdit;
    private String ageS;
    private Button codeBtn;
    private ClearableEditText phoneEdit;
    private String phoneS;
    private Button baomingBtn;
    private String mGameId;
    private String headUrl;
    private LinearLayout vfcode_layout;
    private TextView vf_divider;
    InputMethodManager im;
    private TimeCount time;
    private int getCodeTaskId = -1;
    private static final int PHONE_LENGTH = 11;
    private static final String PHONE_REGEX = "1[34578]\\d{9}";
    private String imageId="";
    private String gameName;
    private int needCode;
    private TextView gameNameText;
    private TextView mAgree;
    private String mNotice;
    private ClearableEditText schoolEdit;
    private String mSchool;
    private RelativeLayout schoolLayout;
    private int needSchoolTaskId  = -1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canjiahuodong);
        mContext = this;
        time = new TimeCount(90000, 1000);
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG"+ System.currentTimeMillis()+".jpeg";
        mFile = new File(folder,fileName);
        initView();
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }
    private void updateUserInfo() {

        userInfo = getEatShowApp().getmUserInfo();
        if(userInfo != null){
            String head_url = userInfo.getUserLogo();
            if(head_url != null && head_url.length()>0 && !head_url.equals(old_url)){
                ImageCache.getInstance(mContext).loadBitmapToView(mHeadImageView,head_url, ViewUtil.getHeadImageSize(mContext));
                old_url = head_url;
            }
            try {
                nickNameText.setText(URLDecoder.decode(userInfo.getNickName(), "utf-8"));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if(!TextUtils.isEmpty(userInfo.getUserSign())){
                try {
                    personSigatureText.setText(URLDecoder.decode(userInfo.getUserSign(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }


            if(userInfo.getSex().equals("true")){
                sexView.setText("男");
            }else {
                sexView.setText("女");
            }

            if (!TextUtils.isEmpty(userInfo.getPhoneNum())){
                phoneEdit.setText(userInfo.getPhoneNum());
                phoneEdit.setEnabled(false);
                phoneEdit.setFocusable(false);
                phoneEdit.setFocusableInTouchMode(false);
                vfcode_layout.setVisibility(View.GONE);
                vf_divider.setVisibility(View.GONE);
                needCode = 0;
            }else {
                phoneEdit.setEnabled(true);
                phoneEdit.setFocusable(true);
                phoneEdit.setFocusableInTouchMode(true);
                vfcode_layout.setVisibility(View.VISIBLE);
                vf_divider.setVisibility(View.VISIBLE);
                needCode = 1;
            }
        }
    }


    private void initView() {
        Intent intent = getIntent();
        if (intent !=null){
            mGameId = intent.getStringExtra("gameId");
            gameName = intent.getStringExtra("gameName");
            mNotice = intent.getStringExtra("url");
        }
        ((TextView)findViewById(R.id.back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        schoolLayout = (RelativeLayout) findViewById(R.id.schoolLayout);
        gameNameText = (TextView) findViewById(R.id.gameName);
        gameNameText.setText(gameName);
        headImgLayout = (RelativeLayout) findViewById(R.id.head_img_layout);
        mHeadImageView = (RoundImageView) findViewById(R.id.head_img);
        nickNameLayout  = (RelativeLayout) findViewById(R.id.nickname_layout);
        nickNameText = (ClearableEditText) findViewById(R.id.nickname);
        personSigatureLayout = (RelativeLayout) findViewById(R.id.person_signature_layout);
        personSigatureText = (ClearableEditText) findViewById(R.id.person_signature);
        //userSex = (ClearableEditText) findViewById(R.id.user_sex);
        mHeadImageView.setOnClickListener(this);
        sexView = (TextView) findViewById(R.id.user_sex);
        sexView.setOnClickListener(this);
//        nickNameLayout.setOnClickListener(this);
//        personSigatureLayout.setOnClickListener(this);
        saveText = (TextView) findViewById(R.id.saveinfo);
        saveText.setOnClickListener(this);
        phoneEdit = (ClearableEditText) findViewById(R.id.phone_edit);
        codeEdit = (ClearableEditText) findViewById(R.id.code_edit);
        ageEdit = (ClearableEditText) findViewById(R.id.age_edit);
        schoolEdit = (ClearableEditText) findViewById(R.id.school_edit);
        baomingBtn = (Button) findViewById(R.id.baoming_btn);
        baomingBtn.setOnClickListener(this);
        vfcode_layout = (LinearLayout) findViewById(R.id.vf_layout);
        vf_divider = (TextView) findViewById(R.id.vf_divider);
        codeBtn = (Button) findViewById(R.id.forget_code_button);
        codeBtn.setOnClickListener(this);
        mAgree = (TextView) findViewById(R.id.agree);
        mAgree.setOnClickListener(this);
        initPopWindow();
        initSexPopWindow();
        isNeedSchool();
        updateUserInfo();
    }


    private void initSexPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_sex,null);
        view.findViewById(R.id.nan).setOnClickListener(this);
        view.findViewById(R.id.nv).setOnClickListener(this);
        mPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setBackgroundDrawable(new ColorDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_sex:

                im.hideSoftInputFromWindow(CanjiahuodongActivity.this.getCurrentFocus().getWindowToken(),0);
                mPopWindow.showAtLocation(v, Gravity.BOTTOM,0,30);
                break;
            case R.id.nan:
                sexView.setText(R.string.sex_nan);
                mPopWindow.dismiss();
                break;
            case R.id.nv:
                sexView.setText(R.string.sex_nv);
                mPopWindow.dismiss();
                break;
            case R.id.head_img:
                im.hideSoftInputFromWindow(CanjiahuodongActivity.this.getCurrentFocus().getWindowToken(),0);
                popWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
                break;
            case R.id.nickname_layout:
                Intent nickname_intent = new Intent(mContext,UpdateNickNameActivity.class);
                startActivity(nickname_intent);
                break;
            case R.id.person_signature_layout:
                Intent signature_intent = new Intent(mContext,UpdateSigature.class);
                startActivity(signature_intent);
                break;
            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
//                Intent intent = new Intent(mContext, PhoneMainActivity.class);
//                startActivityForResult(intent,300);
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;
            case R.id.saveinfo:

                if (checkInput()) {
                    doUpdate();
                }
                break;

            case R.id.baoming_btn:
                if (checkInput()) {
                    doUpdate();
                }
                break;
            case R.id.forget_code_button:
                if (checkInputBeforeSMS()){
                    getPhoneCode();
                }
                break;
            case R.id.agree:
//               Intent aIntent =  WebViewActivity.getIntent(mContext, mNotice);
                Intent aIntent = new Intent(mContext,NoticeActivity.class);
                aIntent.putExtra("url",mNotice);
                startActivity(aIntent);
                break;

            default:
                break;
        }
    }


    private boolean checkInput() {
        mNick = nickNameText.getText().toString();
        mSign = personSigatureText.getText().toString();
        phoneS = phoneEdit.getText().toString();

        ageS = ageEdit.getText().toString();
        mSexString = sexView.getText().toString();
        if(schoolLayout.getVisibility()==View.VISIBLE){
            mSchool = schoolEdit.getText().toString();
            if (ViewUtil.isNull(mSchool)){
                Toast.makeText(mContext, R.string.school_hint, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        }

        if (mSexString.equals("男")){
            sexB = true;
        }else{
            sexB = false;
        }

        if (mNick != null){
            mNick = mNick.trim();
        }

        if (mSign != null){
            mSign = mSign.trim();
        }

        if (ageS != null){
            ageS = ageS.trim();
        }


        if (TextUtils.isEmpty(old_url) && TextUtils.isEmpty(imageId)){
            ToastUtil.showMessage(mContext,R.string.userlogo_hint);
            return false;
        }


        if (!checkInputBeforeSMS()){
            return false;
        }
        if (TextUtils.isEmpty(mNick) || TextUtils.isEmpty(mSign) || TextUtils.isEmpty(phoneS) || TextUtils.isEmpty(ageS)){
            ToastUtil.showMessage(mContext,R.string.message_not_null);
            return  false;
        }

        if (vfcode_layout.getVisibility() == View.VISIBLE){
            codeS = codeEdit.getText().toString();
            if (TextUtils.isEmpty(codeS)){
                Toast.makeText(mContext, R.string.no_code, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        }

        if (TextUtils.isEmpty(mNick)) {
            Toast.makeText(mContext, R.string.no_nick,Toast.LENGTH_SHORT).show();
            return false;
        } else if(TextUtils.isEmpty(mSign)){
            Toast.makeText(mContext, R.string.sigature_not_null,Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }
    private void isNeedSchool(){
        IsNeedSchoolTask nsTask = new IsNeedSchoolTask(mGameId);
        nsTask.addListener(uploadImageListener);
        needSchoolTaskId = getEatShowApp().getTaskManager().addTask(nsTask);
    }
    private void doUpdate(){
        BisaibaomingTask uTask = new BisaibaomingTask(mGameId,phoneS,codeS,mNick,sexB,ageS,mSign,imageId,needCode,mSchool);
        uTask.addListener(uploadImageListener);
        saveTaskId = getEatShowApp().getTaskManager().addTask(uTask);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
                break;

            case CHOOSE_REQUEST:
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                break;

            case CROP_REQUEST:
                if (data == null)
                    return;
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                mHeadImageView.setImageBitmap(bitmap);
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(mFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                        100, out);
                uploadImage(mFile.getAbsolutePath());
                break;

            case 300:
                PalLog.e("返回resultcode",resultCode+"");
                break;

            default:
                break;
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST);
    }

    private void uploadImage(String path){
        if(taskId != -1){return;}
        UpdateIconTask task = new UpdateIconTask(path);
        task.addListener(uploadImageListener);
        taskId = getEatShowApp().getTaskManager().addTask(task);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String url = doPost();
//                System.out.println("头像地址:"+url);
//            }
//        }).start();
    }



    private TaskEventListener uploadImageListener = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskid, int result, Object data) {
            super.handleTaskCompleted(taskid, result, data);
            if(taskid == taskId){

                taskId = -1;
                if(data != null){
                    JSONObject json = (JSONObject) data;
                    String logo_url = json.getString("imageURL");
                    imageId = json.getString("imageId");
                    EatShowUserInfo info = getEatShowApp().getmUserInfo();
                    if (info != null) {
                        getEatShowApp().getmUserInfo().setUserLogo(logo_url);
                        PreferenceManager.getInstance().setCurrentUserAvatar(logo_url);
                        EaseUser user = DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
                        user.setNick(info.getNickName());
                        user.setAvatar(logo_url);
                        DemoHelper.getInstance().saveContact(user);
                    }

                }
                if(mFile.exists()){
                    mFile.delete();
                }
            }else if(taskid == saveTaskId){
                if (data != null){
                    JSONObject json = (JSONObject) data;
                    String message = json.getString("message");
                    DialogUtil.createDialog(mContext, getString(R.string.prompt), message, getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                }
            }else if(taskid == needSchoolTaskId){
                if(data!=null){
                    JSONObject json = (JSONObject) data;
                    String needS = json.getString("needSchool");
                    PalLog.e("是否需要学校",needS);
                    if(needS.equals("false")){
                        schoolLayout.setVisibility(View.GONE);
                        mSchool = "";
                    }
                }
            }

        }

        @Override
        public void handleTaskError(int taskid, int errorCode, String errorMsg) {
            if (errorCode== TaskResultCode.CUSTOME_RESULT_CODE){
                DialogUtil.createDialog(mContext, getString(R.string.prompt), errorMsg, getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
                    }
                });
            }else {
                super.handleTaskError(taskid, errorCode, errorMsg);
            }

            if(taskid == taskId){
                taskId = -1;
            }else if(taskid ==saveTaskId){
                saveTaskId = -1;
            }else if (taskid == getCodeTaskId) {
                getCodeTaskId = -1;
                time.cancelTime();
            }
        }

        @Override
        public void handleTaskMessage(int taskid, Object data) {
            super.handleTaskMessage(taskid, data);
        }
    };

    /**
     * 方法作用：倒计时
     */
    class TimeCount extends CountDownTimer {

        // 参数依次为总时长,和计时的时间间隔
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            codeBtn.setText(mContext.getString(R.string.get_vfcode));
            codeBtn.setClickable(true);
            codeBtn.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            codeBtn.setClickable(false);
            codeBtn.setEnabled(false);
            codeBtn.setText(String.format(
                    mContext.getString(R.string.get_vfcode_new),
                    millisUntilFinished / 1000));
        }

        public void cancelTime() {// 取消计时
            time.cancel();
            codeBtn.setText(mContext.getString(R.string.get_vfcode));
            codeBtn.setClickable(true);
            codeBtn.setEnabled(true);
        }

    }

    private void getPhoneCode() {
        GetVerifyCodeTask task = new GetVerifyCodeTask(phoneS, "3");
        task.addListener(uploadImageListener);
        getCodeTaskId = getEatShowApp().getTaskManager().addTask(task);
        time.start();
    }

    private boolean checkInputBeforeSMS() {
        phoneS = phoneEdit.getText().toString();
        if (TextUtils.isEmpty(phoneS) || phoneS.length() != PHONE_LENGTH
                || !phoneS.matches(PHONE_REGEX)) {
            Toast.makeText(mContext, R.string.no_phone, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }
}
